﻿# -*- coding: utf-8 -*-

class ComparableWave:
  """represents single comparable_wave."""
  def __init__(self, wave_id, wave_title, wave_tags, tags):
    self.wave_id = wave_id
    self.wave_title = wave_title
    self.wave_tags = wave_tags
    self.tags = []
    for group in tags:
      self.tags.append(dict())
      self.tags[-1]["elements"] = [q.lower() for q in group["elements"]] 
    self.tag_indexes = []
    self.__get_indexes()
  
  def __get_indexes(self):
    for i in range(len(self.tags)):
      self.tag_indexes.append(len(self.tags[i]["elements"]) )    
    for tag in self.wave_tags:
      i = 0
      while i < len(self.tags):
        try:
          self.tag_indexes[i] = self.tags[i]["elements"].index(tag.lower()) #create indexes comparing in lowercase
          break
        except ValueError:
          i += 1
  
  def __call__(self, tags):
    """ Changes specified tags and recalculates tag_indexes according to new tags. """
    self.tags = tags
    self.tag_indexes = []
    self.__get_indexes()
    
  def __unicode__(self):  
    return self.wave_title
      
  def __cmp__(self, other):
    begin = True
    for index in range(len(self.tag_indexes)):
      length = len(self.tags[index]["elements"])
      if self.tag_indexes[index] != other.tag_indexes[index] and self.tag_indexes[index] < length and other.tag_indexes[index] < length:
        return cmp(self.tag_indexes[index], other.tag_indexes[index]) #common values
      elif self.tag_indexes[index] > other.tag_indexes[index]:
        if begin:
          return 1
        return -1
      elif self.tag_indexes[index] < other.tag_indexes[index]:
        if begin:
          return -1
        return 1
      if self.tag_indexes[index] != length and self.tag_indexes[index] == other.tag_indexes[index]:
        begin = False
    return 0
    
  @property 
  def end(self):
    tmp = range(len(self.tag_indexes))
    tmp.reverse()
    for i in tmp:
      if self.tag_indexes[i] < len(self.tags[i]["elements"]):
        return i
    return 0
        
  @property 
  def begin(self):  
    for i in range(len(self.tag_indexes)):
      if self.tag_indexes[i] < len(self.tags[i]["elements"]):
        return i
    return len(self.tag_indexes)